package com.hzz.web.boss.analysis;

import com.hzz.api.analysis.IAnalysisEventComplaintService;
import com.hzz.dto.analysis.AnalysisEventComplaintDto;
import com.hzz.framework.PageUtil;
import com.hzz.framework.Response;
import com.hzz.framework.annotation.auth.Logical;
import com.hzz.framework.annotation.auth.RequiresPermissions;
import com.hzz.framework.util.*;
import com.hzz.framework.web.controller.BaseController;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Api("投诉统计")
@RestController
@Slf4j
public class AnalysisComplaintController extends BaseController {
    private static final long serialVersionUID = -528422099490438672L;
    private static final String acPrefix = "/boss/analysis/complaint/";
    @Value("${export.analysis_complaint_treatment}")
    String templateXls;
    @Autowired
    IAnalysisEventComplaintService analysisEventComplaintService;

    @RequiresPermissions(value = {"analysis:complaint:treatment"}, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "area/page/{pageNum}")
    // @ApiOperation(value = "投诉统计-分页")
    public Response analysisNumberByAreaIsPage(@ModelAttribute AnalysisEventComplaintDto dto, @PathVariable("pageNum") Integer pageNum) {
        log.info("analysisNumberByAreaIsPage.........");
        Response result = new Response();
        try {
            dto.setPageSize(5);
            dto.setPageNum(pageNum);
            dto.setReportingType(1);
            result.data = PageUtil.copy(analysisEventComplaintService.analysisNumberByAreaIsPage(dto));
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions(value = {"analysis:complaint:treatment"}, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "area/rate")
    // @ApiOperation(value = "投诉统计-all")
    public Response analysisNumberByArea(@ModelAttribute AnalysisEventComplaintDto dto) {
        log.info("analysisNumberByArea.........");
        Response result = new Response();
        try {
            dto.setReportingType(1);
            result.data = analysisEventComplaintService.analysisNumberByArea(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions(value = {"analysis:complaint:type"}, logical = Logical.OR)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "area/type")
    // @ApiOperation(value = "次级行政区划投诉统计")
    public Response analysisTypeByArea(@ModelAttribute AnalysisEventComplaintDto dto) {
        log.info("analysisTypeByArea.........");
        Response result = new Response();
        try {
            dto.setReportingType(1);
            result.data = analysisEventComplaintService.analysisTypeByArea(dto);
        } catch (Exception e) {
            result = Response.error(e.getMessage());
        }
        return result;
    }

    @RequiresPermissions("analysis:complaint:treatment:export:xls")
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST}, value = acPrefix + "export/xls")
    // @ApiOperation(value = "行政区划投诉统计导出")
    public void analysisEventComplaintExport(@ModelAttribute AnalysisEventComplaintDto dto) throws Exception {
        log.info("analysisEventComplaintExport.........");
        try {
            setResponseHeader(request, response, "投诉统计_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            dto.setReportingType(1);
            List<AnalysisEventComplaintDto> dataIsList = analysisEventComplaintService.analysisNumberByArea(dto);
            //创建模板的副本
            InputStream inputStream = FileUtil.getFileAsInputStream(templateXls);
            File temp = new File(System.getProperty("java.io.tmpdir"), "analysis_complaint_treatment_" + DateUtil.getCurDateStr("yyyyMMddHHmmss") + ".xls");
            FileUtils.copyInputStreamToFile(inputStream, temp);
            //表格s数据填充
            InputStream input = new FileInputStream(temp);
            HSSFWorkbook workBook = new HSSFWorkbook(input);
            Sheet sheet = workBook.getSheetAt(0);
            try {
                for (int i = 0; i < dataIsList.size(); i++) {
                    AnalysisEventComplaintDto data = dataIsList.get(i);
                    //从第2行开始写
                    Row row = sheet.createRow(i + 1);

                    row.createCell(0).setCellValue(StrUtil.asString(data.getAreaName()));// 行政区划
                    row.createCell(1).setCellValue(StrUtil.asString(data.getComplaintsNumber()));// 投诉个数
                    row.createCell(2).setCellValue(StrUtil.asString(data.getSolvedNumber()));// 已解决个数
                    row.createCell(3).setCellValue(StrUtil.asString(data.getComplaintsNumber() - data.getSolvedNumber()));// 未解决个数
                    row.createCell(4).setCellValue(StrUtil.asString(data.getUnsettled5DaysNumber()));// 超5天未解决个数
                    row.createCell(5).setCellValue(StrUtil.asString(ArithUtil.round((data.getSolvedNumber() * 1.0 / data.getComplaintsNumber()) * 100, 2)) + "%");// 处理率
                }
            } catch (Exception e) {
                log.error("excel数据导出填充异常!", e);
            }
            workBook.write(response.getOutputStream());
            workBook.close();
            input.close();
            FileUtil.closeStream(inputStream);
            temp.delete();
        } catch (Exception e) {
            log.error("excel数据导出异常", e);
            WebUtil.sendJson(response, Response.error(500, "excel数据导出异常!" + e.getMessage()));
        }
    }
}